package com.pft.web.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pft.web.App;
import com.pft.web.R;
import com.pft.web.manager.DeviceConnFactoryManager;
import com.pft.web.model.constants.Constant;
import com.pft.web.model.entities.PrintData;
import com.pft.web.view.baseui.BasePermissionActivity;
import com.pft.web.view.contract.BlueToothContract;
import com.pft.web.view.contract.WebViewContract;
import com.pft.web.view.dialog.DialogActionSheet;
import com.pft.web.view.dialog.DialogManager;
import com.pft.web.view.presenter.BlueToothPresenter;
import com.pft.web.view.presenter.WebViewPresenterImp;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;

public class CommonWebViewActivity extends BasePermissionActivity implements WebViewContract.View, BlueToothContract.View {
    public static final String EXTRA_URL = "extra_url";

    public static final String TAG = "CommonWebViewActivity";

    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    public static final int PERMISSION_REQUEST_RESULT_CODE = 111;

    public static final int PHOTO_REQUEST_GALLERY = 2;
    public static final int PHOTO_REQUEST_TAKE_PHOTO = 1;
    private static final int REQUEST_FILE_PICKER = 4;
    private static final int REQUEST_SCAN_QRCODE = 11111;
    private static final int REQUEST_GPS = 5;


    @BindView(R.id.ll_fail)
    ViewGroup failedLayout;
    private WebViewContract.Presenter mPresenter;
    private Uri photoUri;
    @BindView(R.id.ll_success)
    ViewGroup successLayout;
    @BindView(R.id.webview)
    WebView webView;

    List<String> deniedPerms;
    private int deviceId = 0;

    BlueToothContract.Presenter blueToothPresenter;

    @Override
    protected void onCreate(Bundle paramBundle) {

        super.onCreate(paramBundle);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);

        blueToothPresenter = new BlueToothPresenter(this);

    }


    protected void initData() {
        String str1 = getIntent().getStringExtra("extra_url");

        mPresenter = new WebViewPresenterImp(this);
        this.mPresenter.setupWebView(this.webView);
//        webView.loadUrl("file:///android_asset/file.html");
        //http://140.246.77.157:1125
//        this.mPresenter.loadStartUrl(this.webView, "http://140.246.77.157:1125/Meter/Index#");

        this.mPresenter.loadStartUrl(this.webView, str1);

        String[] perms = {LOCATION, ACCESS_COARSE_LOCATION, EXTERNAL_STORAGE, CAMERA, BLUETOOTH, BLUETOOTH_ADMIN};
        performCodeWithPermission("请打开所需要的权限", 1002, perms, new PermissionCallback() {
            @Override
            public void hasPermission(List<String> allPerms) {
//                if (allPerms.contains(LOCATION)) {
//                    startLocation();
//                }
            }

            @Override
            public void noPermission(List<String> deniedPerms, List<String> grantedPerms, Boolean hasPermanentlyDenied) {
                if (deniedPerms != null && !deniedPerms.isEmpty()) {
                    alertAppSetPermission("请前去设置页面打开定位权限", PERMISSION_REQUEST_RESULT_CODE);
                    CommonWebViewActivity.this.deniedPerms = deniedPerms;
                }

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(blueToothPresenter.getReceiver());
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        registerReceiver(blueToothPresenter.getReceiver(), filter);
    }

    private void changeAvatarClick() {

        DialogActionSheet dialog = new DialogActionSheet(this);
        final String[] sexStr = new String[]{"拍照", "相册"};
        for (String menuItem : sexStr) {
            dialog.builder().setCancelable(true).setCanceledOnTouchOutside(false).setTitle("获取图片方式");
            dialog.addSheetItem(menuItem, DialogActionSheet.SheetItemColor.Black, new DialogActionSheet.OnSheetItemClickListener() {

                @Override
                public void onClick(int which) {

                    switch (which) {
                        case 1:
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            ContentValues values = new ContentValues();
                            photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                            startActivityForResult(intent, PHOTO_REQUEST_TAKE_PHOTO);

                            break;
                        case 2:
                            intent = new Intent("android.intent.action.PICK", null);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            CommonWebViewActivity.this.startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

                            break;
                    }
                }
            });
        }
        dialog.show();

    }


    public void closeWebContainer() {
        finish();
    }

    public void dismissLoadingView() {
        dismissLoading();
    }

    public void showLoadingView(String loading) {
        showLoading(loading);
    }

    public void showLoadProgress(int paramInt) {

    }

    public WebView getWebView() {
        return this.webView;
    }


    @Override
    public void showScanQrCode() {
        ScanActivity.launch(this);
    }

    List<PrintData> printData;

    Type typeJson = new TypeToken<List<PrintData>>() {
    }.getType();

    @Override
    public void bluetoothPrint(String data) {
        printData = new Gson().fromJson(data, typeJson);

        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers().length > 0
                && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[deviceId] != null
                && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[deviceId].getConnState()) {
            blueToothPresenter.receiptPrint(printData);
        } else {
            startActivityForResult(new Intent(this, BluetoothDeviceList.class), Constant.BLUETOOTH_REQUEST_CODE);
        }


    }

    @Override
    public void clearMemory() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
                @Override
                public void onReceiveValue(Boolean value) {

                }
            });// Removes all cookies.

        }else {
            CookieSyncManager.createInstance(webView.getContext());
            CookieManager.getInstance().removeAllCookie();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case PERMISSION_REQUEST_RESULT_CODE:
                if (deniedPerms != null) {

                    for (String deniedPerm : deniedPerms) {
                        if (!EasyPermissions.hasPermissions(getApplicationContext(), deniedPerm)) {
                            finish();
                        }
                    }
                }
                break;

            case PHOTO_REQUEST_TAKE_PHOTO:

                if (resultCode == Activity.RESULT_OK) {
                    Intent intent = new Intent();
                    intent.setData(this.photoUri);
                    this.mPresenter.gainFilePicker(resultCode, intent);
                } else {
                    this.mPresenter.gainFilePicker(0, null);
                }
                break;
            case REQUEST_FILE_PICKER:
                if (resultCode == Activity.RESULT_OK) {
                    this.mPresenter.gainFilePicker(resultCode, data);
                } else {
                    this.mPresenter.gainFilePicker(0, null);
                }


                break;
            case PHOTO_REQUEST_GALLERY:
                break;
            case REQUEST_SCAN_QRCODE:

                int state = 0;
                String code = null;
                if (resultCode == RESULT_OK) {
                    code = data.getStringExtra(ScanActivity.RESULT_EXTRA);
                    if (!TextUtils.isEmpty(code)) {
                        state = 1;
                    }
                }
                this.mPresenter.gainScanQrCode(this.webView, state, code);
                break;

            case Constant.BLUETOOTH_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    /*获取蓝牙mac地址*/
                    String macAddress = data.getStringExtra(BluetoothDeviceList.EXTRA_DEVICE_ADDRESS);
                    //初始化话DeviceConnFactoryManager
                    new DeviceConnFactoryManager.Build()
                            .setId(deviceId)
                            //设置连接方式
                            .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH)
                            //设置连接的蓝牙mac地址
                            .setMacAddress(macAddress)
                            .build();
                    //打开端口
                    DeviceConnFactoryManager.getDeviceConnFactoryManagers()[deviceId].openPort();
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            blueToothPresenter.receiptPrint(printData);
                        }
                    }, 1000);

                    break;
                }

                break;
            case REQUEST_GPS:
                startLocation();
                break;


        }

    }


    private List<PrintData> make() {
        List<PrintData> printData = new ArrayList<>();
        PrintData data = new PrintData(0, 0, 0, 1, "温馨提示\n", true);
        printData.add(data);


        data = new PrintData(0, 0, 0, 0, "用户编号：52639376667", true);
        printData.add(data);


        data = new PrintData(0, 0, 0, 0, "地址：打开积分卡进风口付款垃圾分类卡 发货快了发货快发发发发发", false);
        printData.add(data);

        List<PrintData> printData1 = new ArrayList<>();
        data = new PrintData(0, 0, 0, 0, "用户", false);
        printData1.add(data);
        data = new PrintData(0, 0, 0, 0, "地址", false);
        printData1.add(data);
        data = new PrintData(0, 0, 0, 0, "金额", false);
        printData1.add(data);

        data = new PrintData(0, 0, 0, 0, "123456790", false, printData1);
        printData.add(data);


        List<PrintData> printData2 = new ArrayList<>();
        data = new PrintData(0, 0, 0, 0, "张数", false);
        printData2.add(data);
        data = new PrintData(0, 0, 0, 0, "33佛挡杀佛", false);
        printData2.add(data);
        data = new PrintData(0, 0, 0, 0, "123.44", false);
        printData2.add(data);


        data = new PrintData(0, 0, 0, 0, "123456790", false, printData2);
        printData.add(data);


        data = new PrintData(0, 0, 1, 1, "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545752998072&di=eccfdb42589976ba6746d64c8b9782fc&imgtype=0&src=http%3A%2F%2Fimg.atobo.com%2FProductImg%2FEWM%2FUWeb%2F3%2F8%2F2%2F8%2F5294%2F38285294%2F1.gif", false);
        printData.add(data);

        String dd = new Gson().toJson(printData);
        Log.e("lishm",dd);


        return printData;
    }


    @Override
    public void onBackPressed() {
        this.mPresenter.goBack(this.webView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.mPresenter != null) {
            this.mPresenter.destroy();
        }
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers().length > 0
                && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[deviceId] != null
                && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[deviceId].getConnState()) {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[deviceId].closePort(deviceId);
        }

        webView.destroy();
    }

    @Override
    protected void onRestoreInstanceState(Bundle paramBundle) {
        super.onRestoreInstanceState(paramBundle);
        this.webView.restoreState(paramBundle);
    }

    @Override
    protected void onSaveInstanceState(Bundle paramBundle) {
        super.onSaveInstanceState(paramBundle);
        this.webView.saveState(paramBundle);
    }


    public void setCloseVisibility(int paramInt) {
    }

    public void showCallphonePage(Uri paramUri) {
        Intent intent = new Intent("android.intent.action.DIAL", paramUri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void showFailedView() {
        this.successLayout.setVisibility(View.GONE);
        this.failedLayout.setVisibility(View.VISIBLE);
    }


    public void showSuccessView() {
        this.successLayout.setVisibility(View.VISIBLE);
        this.failedLayout.setVisibility(View.GONE);
    }


    Intent pickIntent;

    public void showFilePickerPage(Intent paramIntent) {
        pickIntent = paramIntent;
        runOnUiThread(new Runnable() {
            public void run() {
                CommonWebViewActivity.this.changeAvatarClick();
            }
        });
    }


    public void showTitle(String paramString) {

    }


    LocationManager locationManager;
    Handler mHandler = new Handler();

    Runnable stopRun = new Runnable() {
        @Override
        public void run() {
        }
    };

    @SuppressLint("MissingPermission")
    @Override
    public void startLocation() {
        //获取当前的LocationManager对象
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        boolean isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!isOpen) {
            //进入GPS的设置页面
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent, REQUEST_GPS);
            return;
        }

        showLoading("定位中....");

        AMapLocationClient mLocationClient = new AMapLocationClient(App.getContext());
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setOnceLocation(true);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new LocationListener());


    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showAlterDialog(String message) {
        DialogManager.showAlertDialog(this, message);
    }

    @Override
    public void showAlterDialog(int sId) {
        showAlterDialog(getResources().getString(sId));
    }


    private class LocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {

            dismissLoading();
            int state = 0;
            double latitude = 0;
            double longitude = 0;
            if (aMapLocation.getErrorCode() == 0) {
                state = 1;
                latitude = aMapLocation.getLatitude();
                longitude = aMapLocation.getLongitude();
            }

            mPresenter.gainGps(state, latitude, longitude);
        }
    }

}
